<template>
  <a-modal
    title="添加学生用户"
    :width="600"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <div style="padding-bottom: 20px">每行一名学生用户，学号、姓名间用空格分开。</div>
        <a-form-item>
          <a-textarea :placeholder="tips" v-decorator="['studentList', {rules: [{required: true, message: '请输入学生的学号姓名', trigger: 'blur'}]}]" :rows="10" />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { addStudentList } from '@/api/basic/student'
export default {
  data () {
    return {
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      students: {},
      roleId: '4',
      tips: '学号1 姓名1\n学号2 姓名2'
    }
  },
  methods: {
    add () {
      this.visible = true
    },
    getJsonList (valueList) {
      var that = this
      var students = [] // 以空格空行分开分割成的字符串
      var newStudents = [] // 两两分割的字符串
      var newStudentList = [] // 最终形成的Json数组
      students = valueList.split(/[\s\n]/) // 以空格空行分开
      console.log(students)
      if (students) {
        for (var i = 0; i < students.length; i += 2) {
          newStudents.push(students.slice(i, i + 2))
        }
      }
      console.log(newStudents)
      if (newStudents) {
        for (var j = 0; j < newStudents.length; j++) {
          newStudentList.push({ 'studentCode': newStudents[j][0], 'studentName': newStudents[j][1], 'roleId': that.roleId })
        }
      }
      console.log(newStudentList)
      that.students = JSON.stringify(newStudentList)
      console.log(that.students)
    },
    handleSubmit () {
      const { form: { validateFields } } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        this.getJsonList(values.studentList)
        if (!errors) {
          addStudentList({ 'studentList': this.students })
            .then(res => {
              if (res.message !== 'error') {
                this.visible = false
                this.confirmLoading = false
                this.form.resetFields()
                this.$emit('ok')
              } else {
                this.confirmLoading = false
                this.form.resetFields()
                this.$message.error('操作失败！')
              }
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.form.resetFields()
      this.visible = false
    }
  }
}
</script>
